//////------------Inctech Team version rights--------------------------------
//////------------Creator:        刘少明             ---------------------------------
//////------------Date：                 20150520    -----------------------------------
//////------------Description：一个控制器：里面只包含一个用户的工作流    ---------
//////------------Modify person：     -------------------------------------------

package com.inctech.controller.officeAuto;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.inctech.flowengine.FlowWebservice;
import com.inctech.service.IFlowEngineService;
import com.inctech.service.IPassportService;

@Controller
@RequestMapping("/selfflow")
public class SelfFlowController {
final Logger logger = LoggerFactory.getLogger(SelfFlowController.class);
	
	@Resource(name="flowEngineService")
	private IFlowEngineService flow;
	private FlowWebservice getClient() {
		return flow.getFlowClinet();
	}
	
	@Resource(name = "passportService")
	IPassportService passportService;
	
	@RequestMapping("/selfflowindex")
	public String index() {
		return "officeauto/selfflowindex";
	}
	
	@ResponseBody
	@RequestMapping("/startproc")
	public String startProc(HttpServletRequest request) {
		String procKey = "ECommerce";
		HttpSession session = request.getSession();
		String usr = session.getAttribute("currentUser").toString();
		String procInfo = this.getClient().startUserTaskProcInstance(procKey, usr);
		return procInfo;
	}
	
	@ResponseBody
	@RequestMapping("/queryallprocs")
	public String queryAllProcs(int page, int rows) {
		//当为缺省值的时候进行赋值
        int currentpage = ( page == 0) ? 1: page;	//第几页
        int pagesize = (rows == 0) ? 5: rows;	//每页显示数量
        int index = (currentpage - 1) * pagesize;	//从第几条开始显示
        String jsonString = "";
        try {
        	jsonString = this.getClient().queryProcInstances(index, pagesize);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("出错了", e);
		}
		return jsonString;
	}
	
	@ResponseBody
	@RequestMapping("/completeprocinst")
	public String completeProccessInstance(String procId) {
		String status = this.getClient().completeProccessInstance(procId);
		return status;
	}
	
	//获取当前用户的所有Task
	@ResponseBody
	@RequestMapping("/gettasks")
	public String getTasks(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String userId = session.getAttribute("currentUser").toString();
		String jsonArray = this.getClient().queryTasksByUser(userId);
		return jsonArray;
	}
	
//	passportService
	//获取当前用户的所有Task
	@ResponseBody
	@RequestMapping("/gettaskstest")
	public String getCandidateTasks(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String userId = session.getAttribute("currentUser").toString();
		String jsonArray =passportService.getGoupIdByUserId(userId);
		return jsonArray;
	}
	
//	getAllUserIds
	//获取当前用户的所有Task
	@ResponseBody
	@RequestMapping("/gettaskform")
	public String getTaskForm(String taskId) {
		String variables = this.getClient().getFormByTaskId(taskId);
		JSONObject variablesObj = JSONObject.fromObject(variables);
		//progressAxis表示当前流程的流转进度显示，里面会包含这个流程实例中的所有节点
		String progress = this.getClient().getAllTaskNodesAndNextNode(taskId);
		System.out.println("progress axis:" + progress);
		JSONArray progressArray = JSONArray.fromObject(progress);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String taskName = this.getClient().queryTaskNameByTaskId(taskId);
		
		List<String> userIds = passportService.getAllUserIds();
		if(taskName.indexOf(".") > -1)
			taskName = taskName.split("\\.")[1];
		resultMap.put("formData", variablesObj);
		resultMap.put("progressAxis", progressArray);
		resultMap.put("currentNode", taskName);
		resultMap.put("nextHandlers", userIds);
		String json = JSONObject.fromObject(resultMap).toString();
		return json;
	}
	
	@ResponseBody
	@RequestMapping("/completetaskwithform")
	public String completeTaskWithForm(String drafter, String startDate, String term, 
			String reason, String taskId, HttpServletRequest request) {
		HttpSession session = request.getSession();
		String nextHandler = session.getAttribute("currentUser").toString();
		Map<String, Object> formMap = new HashMap<String, Object>();
		formMap.put("drafter", request.getParameter("drafter"));
		formMap.put("startDate", request.getParameter("startDate"));
		formMap.put("startTime", request.getParameter("startTime"));
		formMap.put("commodity", request.getParameter("commodity"));
		formMap.put("amount", request.getParameter("amount"));
		formMap.put("postAddr", request.getParameter("postAddr"));	
		String formJson = JSONObject.fromObject(formMap).toString();
		String status = this.getClient().completeTaskByTaskIdWithVariables(taskId, formJson, nextHandler);
		return status;
	}
}
